//
//  SellerServiceDemotionViewController.m
//  nonghubao
//
//  Created by Fenrir on 13-11-12.
//  Copyright (c) 2013年 Chongqing Nonghubao Co., Ltd. All rights reserved.
//

#import "SellerServiceDemotionViewController.h"
#import "JSONRequest.h"
#import "JMFBase.h"
#import <QuartzCore/QuartzCore.h>
#import "SZTextView.h"

@interface SellerServiceDemotionViewController ()<UIWebViewDelegate, JSONRequestDelegate, UIAlertViewDelegate, UITextViewDelegate>

@end

@implementation SellerServiceDemotionViewController
{
    UIScrollView *_scrollView;
    UIWebView *_webView;
    BOOL _isExistReq;
    NSString *_demotionReqTime;
    NSInteger _demotionId;
    
    SZTextView *_reasonTextView;
    UIButton *_applyButton;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    self.title = _L(@"vc_title_108");
    
    self.view.backgroundColor = [UIColor whiteColor];
     
    //返回按钮
    UIButton *backButton = [Helper buttonWithStyle:ButtonStyleNavigationReturn];
    [backButton addTarget:self action:@selector(backButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, _SYS_FRAME_HEIGHT)];
    
    _scrollView.contentSize = CGSizeMake(320.0f, _SYS_SCREEN_HEIGHT+150);
    
    [self.view addSubview:_scrollView];
    
    _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, _SYS_FRAME_WIDTH, _SYS_FRAME_HEIGHT-80)];
    
    if (iPhone5) {
        _scrollView.contentSize = CGSizeMake(320.0f, _SYS_SCREEN_HEIGHT);
        _webView.frame = CGRectMake(0, 0, _SYS_FRAME_WIDTH, _SYS_FRAME_HEIGHT-160);
    }
    
    _webView.delegate = self;
    _webView.scrollView.scrollEnabled = NO;
    [_scrollView addSubview:_webView];
    
    _reasonTextView = [[SZTextView alloc] initWithFrame:CGRectMake(10.0f, Y_AND_HEIGHT(_webView.frame)+5, 300.0f, 85.0f)];
    if (iOS5) {
        _reasonTextView.frame = CGRectMake(10.0f, Y_AND_HEIGHT(_webView.frame)+10.0f, 300.0f, 85.0f);
    }
    _reasonTextView.layer.cornerRadius = 3.0f;
    _reasonTextView.layer.borderWidth = 1.0f;
    _reasonTextView.delegate = self;
    _reasonTextView.hidden = YES;
    _reasonTextView.returnKeyType = UIReturnKeyDone;
    _reasonTextView.layer.borderColor = RGBCOLOR(200, 200, 200).CGColor;
    _reasonTextView.font = _SYS_FONT_003;
    _reasonTextView.placeholder = _L(@"holder_59");
    _reasonTextView.placeholderTextColor = [UIColor lightGrayColor];
    [_scrollView addSubview:_reasonTextView];
    
    _applyButton = [[UIButton alloc] initWithFrame:CGRectMake(10.0f, Y_AND_HEIGHT(_reasonTextView.frame)+10.0f, 300.0f, 40.0f)];
    _applyButton.hidden = YES;
    [_applyButton setBackgroundImage:[UIImage imageNamed:@"com_btn_006_n"] forState:UIControlStateNormal];
    [_applyButton addTarget:self action:@selector(applyButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    [_applyButton setTitle:_L(@"btn_yes_48") forState:UIControlStateNormal];
    [_scrollView addSubview:_applyButton];
    
    [self demotionInfoRequest];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 事件

- (void)backButtonEvent
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)applyButtonEvent:(id)sender
{
    if ([_reasonTextView.text length] == 0) {
        
        [Helper showAlertWithTitle:nil andMessage:_L(@"alert_134")];
        return;
    }
    
    [_reasonTextView resignFirstResponder];
    
    //提交降级申请
    JSONRequest *request = [[JSONRequest alloc] initWithURLString:_JSON_URL_ACCOUNT_SELLER_DEMOTE_APPLY];
    request.delegate = self;
    [request setValue:_reasonTextView.text forParameter:@"reason"];
    [request asynchronous];
}

#pragma mark - 私有方法

//获取降级信息
//可能存在没有降级申请和有降级申请两种情况
- (void)demotionInfoRequest
{
    JSONRequest *request = [[JSONRequest alloc] initWithURLString:_JSON_URL_ACCOUNT_SELLER_DEMOTE_APPLY_INFO];
    request.delegate = self;
    [request setSuccessSelector:@selector(demotionInfoDidReceived:)];
    [request asynchronous];
}


#pragma mark - UIWebView Delegate

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    if (_isExistReq) {
        _scrollView.scrollEnabled = NO;
        _reasonTextView.hidden = YES;
        _applyButton.hidden = YES;
        //存在着降级申请就显示出申请时间，传递时间给HTML
        [_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"applyTime.innerHTML='%@'",[Helper localizeDateString:_demotionReqTime]]];
    }
    else {
        _reasonTextView.hidden = NO;
        _applyButton.hidden = NO;
    }

}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSString *url = request.URL.relativeString;
    
    if ([url isEqualToString:@"req:demotion_cancel"] && _isExistReq) {
        
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:_L(@"alert_135") delegate:self cancelButtonTitle:_L(@"btn_no_01") otherButtonTitles:_L(@"btn_yes_01"), nil];
        [alertView show];
    }
    
    return YES;
}

#pragma mark - JSONRequestDelegate

// 降级请求成功

- (void)requestDidLoadJSON:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    if (jmf.status == JMStatusSucceed) {
        
        [Helper showAllTextDialog:jmf.message inSeconds:1.5f];

        if (_isExistReq) {
            
            [self.navigationController popViewControllerAnimated:YES];
        }
        else {
            [self.navigationController popToRootViewControllerAnimated:YES];
            
        }
    }
    else {
        [Helper easyShowJMFStatus:jmf];
        
    }
}

//获取降级请求成功
- (void)demotionInfoDidReceived:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
//    NSLog(@"%@",jmf.data);
    if (jmf.status == JMStatusSucceed) {
        
        NSString* filePath;
        
        //不存在降级申请
        if ([jmf.data count] == 0) {
            
            _isExistReq = NO;
            
            filePath = [[NSBundle mainBundle] pathForResource:@"demotion_req" ofType:@"html"];
        }
        
        //存在降级申请
        else {
            
            _isExistReq = YES;
            
            _demotionReqTime = jmf.data[@"applyTime"];
            
            _demotionId = [jmf.data[@"id"] integerValue];
            
            filePath = [[NSBundle mainBundle] pathForResource:@"demotion_cancel_req" ofType:@"html"];
        }
        
        [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:filePath]]];
    }
    else {
        [Helper easyShowJMFStatus:jmf];
    }
}

// 请求失败
//
- (void)requestFailWithNetworkUnavailabe
{
    [Helper showAlertWithTitle:nil andMessage:_L(@"title_networkunavailabe")];
}

#pragma mark - UIAlertView Delegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        JSONRequest *request = [[JSONRequest alloc] initWithURLString:_JSON_URL_ACCOUNT_SELLER_DEMOTE_APPLY_CANCEL];
        [request setValue:@(_demotionId) forParameter:@"applyId"];
        request.delegate = self;
        [request asynchronous];
    }
}

- (void)textViewDidBeginEditing:(UITextView *)textView
{
    
    [UIView animateWithDuration:0.5f animations:^{
        if (iPhone5) {
            _webView.frame = CGRectMake(0, _scrollView.contentOffset.y-280, _SYS_FRAME_WIDTH, _webView.frame.size.height);
        }
        else {
            _webView.frame = CGRectMake(0, _scrollView.contentOffset.y-360, _SYS_FRAME_WIDTH, _webView.frame.size.height);
        }
        
        if (iOS5) {
            _reasonTextView.frame = CGRectMake(10.0f, Y_AND_HEIGHT(_webView.frame)+10.0f, 300.0f, 85.0f);
        }else{
            _reasonTextView.frame = CGRectMake(10.0f, Y_AND_HEIGHT(_webView.frame), 300.0f, 85.0f);
        }
        _applyButton.frame = CGRectMake(10.0f, Y_AND_HEIGHT(_reasonTextView.frame)+10.0f, 300.0f, 40.0f);
    }];
}

- (void)textViewDidEndEditing:(UITextView *)textView
{
    [UIView animateWithDuration:0.5f animations:^{

        _webView.frame = CGRectMake(0, 0, _SYS_FRAME_WIDTH, _webView.frame.size.height);
        
        if (iOS5) {
            _reasonTextView.frame = CGRectMake(10.0f, Y_AND_HEIGHT(_webView.frame)+10.0f, 300.0f, 85.0f);
        }else{
            _reasonTextView.frame = CGRectMake(10.0f, Y_AND_HEIGHT(_webView.frame), 300.0f, 85.0f);
        }
        _applyButton.frame = CGRectMake(10.0f, Y_AND_HEIGHT(_reasonTextView.frame)+10.0f, 300.0f, 40.0f);
    }];
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"]) {
        [_reasonTextView resignFirstResponder];
    }
    return YES;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [_reasonTextView resignFirstResponder];
}
@end
